<template>
  <div class="order-container">
    <h1>订单管理</h1>

    <!-- 订单列表 -->
    <el-table 
      :data="tableData" 
      border 
      stripe 
      style="width: 100%;"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column prop="orderId" label="订单 ID" width="100" />
      <el-table-column prop="userId" label="用户 ID" width="100" />
      <el-table-column prop="goodsId" label="商品 ID" width="100" />
      <el-table-column prop="quantity" label="数量" width="80" />
      <el-table-column prop="unitPrice" label="单价" width="100">
        <template #default="scope">
          ¥{{ Number(scope.row.unitPrice).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="总价" width="120">
        <template #default="scope">
          <span>¥{{ Number(scope.row.totalPrice).toFixed(2) }}</span>
          <span class="total-hint" v-if="scope.row.totalPrice !== calculateTotal(scope.row)">
            <el-tooltip content="总价与单价×数量不符">
              <i class="el-icon-warning-outline"></i>
            </el-tooltip>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="150">
        <template #default="scope">
          <el-select 
            v-model="scope.row.orderStatus" 
            @change="updateOrderStatus(scope.row.orderId, scope.row.orderStatus)"
            placeholder="请选择"
          >
            <el-option value="待付款">待付款</el-option>
            <el-option value="待发货">待发货</el-option>
            <el-option value="已发货">已发货</el-option>
            <el-option value="已完成">已完成</el-option>
            <el-option value="申请退款">申请退款</el-option>
            <el-option value="已退款">已退款</el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200">
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="200">
        <template #default="scope">
          {{ formatTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <!-- 移除"操作"列 -->
    </el-table>

    <!-- 空状态 -->
    <div v-if="tableData.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无订单数据" />
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElTooltip, ElEmpty } from 'element-plus';

export default {
  name: 'OrderView',
  components: { ElTooltip, ElEmpty },
  data() {
    return {
      tableData: [],
      loading: false,
      baseUrl: 'http://127.0.0.1:8080'
    }
  },
  mounted() {
    this.getOrders();
  },
  methods: {
    // 获取所有订单
    async getOrders() {
      this.loading = true;
      try {
        const res = await axios.get(`${this.baseUrl}/orders/admin/all`, {
          headers: { Authorization: `admin_${localStorage.getItem('adminToken')}` }
        });
        this.tableData = res.data || [];
      } catch (error) {
        const msg = error.response?.data || '获取订单失败';
        ElMessage.error(`错误：${msg}`);
        console.error('获取订单失败:', error);
        this.tableData = [];
      } finally {
        this.loading = false;
      }
    },

    // 计算总价（用于校验）
    calculateTotal(row) {
      return (Number(row.unitPrice || 0) * Number(row.quantity || 0)).toFixed(2);
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    // 更新订单状态
    async updateOrderStatus(orderId, status) {
      try {
        await axios.put(`${this.baseUrl}/orders/status`, null, {
          params: { orderId, orderStatus: status },
          headers: { Authorization: `admin_${localStorage.getItem('adminToken')}` }
        });
        ElMessage.success('状态更新成功');
        this.getOrders();
      } catch (error) {
        ElMessage.error(`更新失败：${error.response?.data || '服务器错误'}`);
        console.error('更新状态失败:', error);
        this.getOrders();
      }
    },

    // 完全移除deleteOrder方法
  }
}
</script>

<style scoped>
.order-container {
  padding: 20px;
}
.total-hint {
  margin-left: 5px;
  color: #f56c6c;
}
.empty-state {
  margin: 50px 0;
  text-align: center;
}
::v-deep .el-table {
  margin-top: 15px;
}
</style>